/**
 * UserDeviceService.java
 * com.ebook.server.service
 * Copyright (c) 2013, 公司版权所有.
*/

package com.ebook.server.service;

import java.io.File;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户设备关系业务service层
 * @author    潘吉友
 * @Date	 2013-5-30 	 
 */
@Service
public class UserDeviceService {
	
	private static final String BOOK_AFTER_UNZIP_PATH = "/opt/ebook/data/ebooks/after_unzip/";
	private static final String BOOK_ZIP_PATH = "/opt/ebook/data/ebooks/zip/";

	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private static Log logger = LogFactory.getLog(UserDeviceService.class);
	
	public boolean isExist(int userId, String device_id) {
		String selectSql = "select count(*) from device_user where user_id=? and device_id=?";
		logger.info(selectSql);
		return jdbcTemplate.queryForInt(selectSql, userId,device_id) > 0 ? true : false;
	}
	
	public void add(int userId, String device_id) {
		if(isExist(userId, device_id)){
			return ;
		}
		String sql = "insert into device_user (device_id,user_id) values (?,?)";
		logger.info(sql);
		jdbcTemplate.update(sql, device_id,userId);
	}
	
	

	public int queryCount(int userId) {
		String sql = "select count(*) from device_user where user_id=? ";
		logger.info(sql);
		return jdbcTemplate.queryForInt(sql, userId);
	}
	
	
	public void delete(String deviceId){
		if(deviceId == null || "".equals(deviceId)){
			return ;
		}
		String sql = "delete from device_user where device_id=?";
		jdbcTemplate.update(sql, deviceId);
	}

	public void delFilePath(int uid, String deviceId) {
		StringBuilder unZipPath = new StringBuilder(BOOK_AFTER_UNZIP_PATH);
		unZipPath.append(uid).append("/").append(deviceId);
		StringBuilder zipPath = new StringBuilder(BOOK_ZIP_PATH);
		zipPath.append(uid).append("/").append(deviceId);
		try{
			FileUtils.deleteDirectory(new File(unZipPath.toString()));
			FileUtils.deleteDirectory(new File(zipPath.toString()));
		}catch(Exception e){
			logger.error("删除文件路径错误！"+e);
		}
		
	}
}

